package com.ruolin.micro.gateway.server.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.ruolin.micro.gateway.server.metadata.ApplicationRouteMetadata;
import com.ruolin.micro.gateway.server.utils.GatewayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;

@Component
public class RemoteRefreshRouteListener implements Listener, EnvironmentAware {
    private Environment environment;
    private volatile AtomicBoolean updated = new AtomicBoolean(true);

    @Autowired
    private ConfigService configService;

    @Override
    public Executor getExecutor() {
        return null;
    }

    @Override
    public void receiveConfigInfo(String configInfo) {
        if (updated.get()) {
            updated.set(false);
        } else {
            updated.set(true);
        }

        if (updated.get()) {
            ApplicationRouteMetadata routeMetadata = JSON.parseObject(configInfo, ApplicationRouteMetadata.class, Feature.values());
            ApplicationRouteMetadata applicationRouteMetadata = GatewayUtils.buildMetadata(routeMetadata.getParameters(), configService, environment);
        }

        System.out.println(configInfo);
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
}
